#! /bin/bash

# read path from first argument
path=$1
scale=$2
pushd $path
#  find dslProgram.txt
file=$(find . -name "dslProgram.txt")
# read first line from file
line=$(head -n 1 $file)
# match it with `void .*(.*)` pattern, and extract the first group
entry=$(echo $line | awk '{match($0, /void ([^()]*)/, arr); print arr[1]}')

# if entry is not main, generate main for dslProgram.txt
if [ "$entry" != "main" ]; then
  # find all files with Main prefix excluding MainClasses.txt and extract the file name without extension
  mainfiles=$(find . -name "Main*.txt" | grep -v "MainClasses.txt" | awk -F/ '{print $NF}' | awk -F. '{print $1}')
  # all mainfile are Main+Num, num start at 0, find the max num
  maxnum=$(echo $mainfiles | tr ' ' '\n' | awk -FMain '{print $2}' | sort -n | tail -n 1)

  func="void main() {"
  # generate maini.f() from 0 to maxnum and append to func
  for i in $(seq 0 $maxnum); do
      func="$func\nMain$i.f();"
  done
  func="$func\nLoop(index, 0, $scale, 1) {"
  func="$func\n$entry(null);"
  func="$func\n}\n}\n"

  # add func to head of dslProgram.txt
  sed -i "1i$func" $file
fi
popd

#javac Main.java
#java Main -Xlog:gc
##PID=$!
##watch -n 0.1 jmap -histo $PID

